#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

install_packages()
{
	local packages
	if [ -f /tmp/packages-to-install ]; then
		packages=$(</tmp/packages-to-install)
	fi
	[ -z "$packages" ] && return 0
	
	echo "Installing packages: $packages"
	
	yum -y install --skip-broken $packages
	yum clean all
}

setup_rootfs()
{
	ln -fs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
	rm -f /etc/machine-id /var/lib/dbus/machine-id
	systemd-machine-id-setup
	
	echo "Disable selinux"
	if [ -f /etc/selinux/config ]; then
		sed -i -r 's/^.*SELINUX=enforcing.*$/SELINUX=disabled/g' "/etc/selinux/config"
	else
		cat > "/etc/selinux/config" <<-EOF
		SELINUX=disabled
		SELINUXTYPE=targeted
		EOF
	fi
}

setup_login() {
	[ -n "$ROOT_PASSWD" ] || return
	echo "Changing root password"
	passwd_md5=$(openssl passwd -1 "$ROOT_PASSWD")
	sed -i -r "s/^root:[^:]*:(.*)/root:${passwd_md5//\//\\/}:\1/" "$ROOTFS_DIR/etc/shadow"

	sed -i 's/[# ]PermitRootLogin.*/PermitRootLogin yes/' "$ROOTFS_DIR/etc/ssh/sshd_config"
}

pack_cgz()
{
	echo "Packing package. Please wait."
	find ./ ! -path "./tmp/${INITRD_NAME}" | grep -vf ./tmp/files-to-exclude | cpio -o -Hnewc | gzip -9 > ./tmp/${INITRD_NAME}
	chmod 644 /tmp/${INITRD_NAME}
}

install_packages
setup_rootfs
setup_login
pack_cgz
